<?php
namespace trade\common\gather;

use think\facade\Db;
use Yii;
use addons\TfFutures\services\OrderService;
use addons\TfFutures\common\models\Order;
use trade\common\service\KlineService;


class GatherRandom_TfFutures extends GatherRandom
{
    public function listen($symbol,$prex){
		$this->listen_hold_order($symbol['code2'],$symbol['ticket']['price'],$symbol['unit_price']);
		$kline  = new KlineService();
        $ticket = $kline->loadTicekt($symbol['code'],'tf_futures_trade');
		$this->listen_pending($symbol['code2'],$ticket);
		
	}
    
    //持仓订单监听——自动平仓
    public function listen_hold_order($symbolid,$price,$unit_price){
        //更新订单所有盈亏
        Yii::$app->db->createCommand(
            "UPDATE `rf_addon_tf_futures_order` SET 
                `profit` = if(`rise_fall`='RISE',{$price} - `open_price`,`open_price` - {$price}) * `volume` * {$unit_price}, 
                `close_price` = {$price} 
            WHERE `symbol` = '{$symbolid}' AND `state` = '持仓' AND `status` = 1
        ")->execute();

        //监听所有订单

        $orders = Db::query(
            "SELECT * FROM `rf_addon_tf_futures_order` WHERE `symbol` = '{$symbolid}' AND `state`='持仓' AND `status` = 1 AND
        `rise_fall`='RISE' AND (
            ( `stop_profit_price` > 0 && {$price} >= `stop_profit_price`) OR
            ( `stop_loss_price`   > 0 && {$price} <= `stop_loss_price`)
        )");
        if (!empty($orders)) {
            foreach ($orders as $order => $v) {
                if( $v['stop_profit_price']>0 && $price >= $v['stop_profit_price'] )
                {
                    OrderService::OrderClose($v['id'],$price,'自动平仓');
                }else if( $v['stop_loss_price']>0 && $price <= $v['stop_loss_price'] )
                {
                    OrderService::OrderClose($v['id'],$price,'自动平仓');
                }
            }
        }
        $orders = Db::query(
            "SELECT * FROM `rf_addon_tf_futures_order` WHERE `symbol` = '{$symbolid}' AND `state`='持仓' AND `status` = 1 AND 
        `rise_fall`='FALL' AND (
            ( `stop_profit_price` > 0 && {$price} <= `stop_profit_price`) OR
            ( `stop_loss_price`   > 0 && {$price} >= `stop_loss_price`)
        )");

        if (!empty($orders)) {
            foreach ($orders as $order => $v) {
                if( $v['stop_profit_price']>0 && $price <= $v['stop_profit_price'] )
                {
                    OrderService::OrderClose($v['id'],$price,'自动平仓');
                }else if( $v['stop_loss_price']>0 && $price >= $v['stop_loss_price'] )
                {
                    OrderService::OrderClose($v['id'],$price,'自动平仓');
                }
            }
        }
    }
    
    public function PendingToPosition($order,$price,$bijiao = 'GT'){
    	
		switch($order['price_type']){
			case 1:
				$price = $price['price'];
				break;
			case 2:
				$price = $price['bid'];
				break;	
			case 3:
				$price = $price['ask'];
				break;	
		}
		if($bijiao == 'GT' && $order['price'] <= $price){
			OrderService::PendingToPosition($order['id']);
		}elseif($bijiao == 'LT' && $order['price'] >= $price){
			OrderService::PendingToPosition($order['id']);
		}
    }
    
    public function CloseOrder($order,$price,$orderss,$bijiao = 'GT'){
    	switch($order['price_type']){
			case 1:
				$price = $price['price'];
				break;
			case 2:
				$price = $price['bid'];
				break;	
			case 3:
				$price = $price['ask'];
				break;	
		}
		if($bijiao == 'GT' && $order['price'] <= $price){
			foreach ($orderss as $k => $value){
				OrderService::OrderClose($value['id'],$price,'自动平仓');
			}
		}elseif($bijiao == 'LT' && $order['price'] >= $price){
			foreach ($orderss as $k => $value){
				OrderService::OrderClose($value['id'],$price,'自动平仓');
			}
		}
    }

    //挂单订单监听
    public function listen_pending($symbolid,$price){
    	
        $orders = Db::query("SELECT * FROM `rf_addon_tf_futures_order_reason` WHERE `symbol` = '{$symbolid}' AND `state`='挂单' AND `limit`='GT'");

        if (!empty($orders)) {
            foreach ($orders as $order){
            	//开仓
            	if($order['type'] == 1){
            		$this->PendingToPosition($order,$price);
            	}else{
            		//平仓
            		if($order['rise_fall'] == 'RISE'){
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'RISE'])->asArray()->all();
            		}elseif($order['rise_fall'] == 'FALL'){
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'FALL'])->asArray()->all();
            		}
            		$this->CloseOrder($order,$price,$orderss);
            		
            	}
            }
        }
        //设定价格是小于的
        $orders = Db::query("SELECT * FROM `rf_addon_tf_futures_order_reason` WHERE `symbol` = '{$symbolid}' AND `state`='挂单' AND `limit`='LT'");
        if (!empty($orders)) {
            foreach ($orders as $order){
            if($order['type'] == 1){
            		$this->PendingToPosition($order,$price,'LT');
            	}else{
            		if($order['rise_fall'] == 'RISE'){
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'RISE'])->asArray()->all();
            		}else{
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'FALL'])->asArray()->all();
            		}
            		$this->CloseOrder($order,$price,$orderss,'LT');
            	}
            }
        }
        $orders = Db::query("SELECT * FROM `rf_addon_tf_futures_order_reason` WHERE `state`='挂单' AND `expiration` <= '".date('Y-m-d H:i:s')."'");
        if (!empty($orders)) {
            foreach ($orders as $order){
                Db::execute("UPDATE `rf_addon_tf_futures_order_reason` SET `state`='删除' WHERE `id`={$order['id']}");
            }
        }
    }
}